import Vue from 'vue'
import axios from 'axios'
import store from '@/store'
import { VueAxios } from './axios'
import { Modal, notification } from 'ant-design-vue'
import { ACCESS_TOKEN, TENANT_ID, GUEST_ACCESS_TOKEN } from '@/store/mutation-types'
import signMd5Utils from '@/utils/encryption/signMd5Utils'
import router from '@/router'
import device from 'current-device'

/**
 * 【指定 axios的 baseURL】
 * 如果手工指定 baseURL: '/jeecg-boot'
 * 则映射后端域名，通过 vue.config.js
 * @type {*|string}
 */
let apiBaseUrl = window._CONFIG['domianURL'] || '/api'
//console.log("apiBaseUrl= ",apiBaseUrl)
// 创建 axios 实例
const service = axios.create({
  baseURL: apiBaseUrl, // api base_url
  timeout: 15000, // 请求超时时间
  withCredentials: false,
})
const homeSortAPIList = [
  '/goods/hTGoods/pc-home-list',
  '/news/hTNews/pc-home-list',
  '/ability/hTAbilityDemand/pc-home-list',
  '/ability/hTAbilitySupply/pc-home-list',
  '/patent/hTPatentDemand/pc-home-list',
  '/patent/hTPatentSupply/pc-home-list',
  '/forums/hTForumsQuestion/pc-home-list',
  '/industry/hTIndustryMeeting/pc-home-list',
  '/industry/hTIndustryExhibition/pc-home-list',
  '/industry/hTIndustrySalon/pc-home-list',
  '/settings/hTCooperationBrand/pc-home-list',
]
const iMAPIList = ['/im/iMMessage/list', '/sys/common/upload', '/support/hTCustomerSupport/getPlatformSupportInfo']

const sortAPIList = [
  '/news/hTNewsCategory/list',
  '/news/hTNews/list',
  '/ability/hTAbilityCategory/list',
  '/ability/hTAbilityDemand/list',
  '/ability/hTAbilitySupply/list',
  '/alliance/hTAllianceTrendsCategory/list',
  '/alliance/hTAllianceTrends/list',
  '/patent/hTPatentCategory/list',
  '/patent/hTPatentDemand/list',
  '/patent/hTPatentSupply/list',
  '/goods/hTGoodsCategory/list',
  '/goods/hTGoods/list',
  '/library/hTLibraryCategory/list',
  '/library/hTLibrary/list',
  '/project-cooperation/hTProjectCooperationCategory/list',
  '/project-cooperation/hTProjectCooperation/list',
  // "/forums/hTForumsQuestion/list",
  '/forums/hTForumsCategory/list',
  '/forums/hTForumsExpertCategory/list',
  '/account/hTForumsExpert/list',
  '/position/hTPositionCategory/list',
  '/position/hTPosition/list',
  '/about/hTHonorCer/list',
  '/industry/hTIndustryMeeting/list',
  '/industry/hTIndustryExhibition/list',
  '/industry/hTIndustrySalon/list',
]

const analyticsTrackAPIList = [
  '/analytics/hTPlatformVisitAction/add',
  '/analytics/hTGoodsDetailVisitAction/add',
  '/analytics/hTNewsDetailVisitAction/add',
]

const err = (error) => {
  // console.info(`\n\n-------- error Info Begin --------\n\n`, error, `\n\n-------- error Info end   --------\n\n`)
  if (error.response) {
    let data = error.response.data
    const token = Vue.ls.get(ACCESS_TOKEN)
    console.log('------异常响应------', token)
    console.log('------异常响应------', error.response.status)
    switch (error.response.status) {
      case 403:
        notification.error({ message: '系统提示', description: '拒绝访问', duration: 4 })
        break
      case 500:
        {
          console.log('------error.response------', error.response)
          const type = error.response.request.responseType
          if (type === 'blob') {
            blobToJson(data)
            break
          }
          // notification.error({ message: '系统提示', description: 'Token失效，请重新登录!', duration: 4 })
          if (token && data.message.includes('Token失效')) {
            // Vue.ls.remove(ACCESS_TOKEN);
            // window.location.reload();
            //       }
            // update-begin- --- author:scott ------ date:20190225 ---- for:Token失效采用弹框模式，不直接跳转----
            // Modal.error({
            //   title: '登录已过期',
            //   content: '很抱歉，登录已过期，请重新登录',
            //   okText: '重新登录',
            //   mask: false,
            //   onOk: () => {
            //     store.dispatch('Logout').then(() => {
            //       Vue.ls.remove(ACCESS_TOKEN)
            //       try {
            //         let path = window.document.location.pathname
            //         console.log("location pathname -> "+path)
            //         if(path!="/" && path.indexOf('/user/login')==-1){
            //           window.location.reload()
            //         }
            //       }catch (e) {
            //         window.location.reload()
            //       }
            //     })
            //   }
            // })
          }
        }

        break

      case 404:
        notification.error({ message: '系统提示', description: '很抱歉，资源未找到!', duration: 4 })
        break
      case 504:
        notification.error({ message: '系统提示', description: '网络超时' })
        break
      case 401:
        // notification.error({ message: "系统提示", description: "未授权，请重新登录", duration: 4 });
        if (token) {
          store.dispatch('user/signOutAction').then(() => {
            setTimeout(() => {
              window.location.reload()
            }, 1500)
          })
        }
        break
      default:
        notification.error({
          message: '系统提示',
          description: data.message,
          duration: 4,
        })
        break
    }
  }
  return Promise.reject(error)
}

// request interceptor
service.interceptors.request.use(
  (config) => {
    var token = Vue.ls.get(ACCESS_TOKEN)

    if (iMAPIList.indexOf(config.url) > -1) {
      if (config.data && config.data.chatType == 0) {
        token = Vue.ls.get(GUEST_ACCESS_TOKEN)
      }
    }

    var channel = '0'
    const timestamp = signMd5Utils.getDateTimeToString()
    var sharedParams = {
      _t: timestamp,
      column: 'createTime',
      order: 'desc',
      isLocked: '0',
      auditStatus: '2',
    }

    // 这里顺序一定要在column: 'createTime'设置之后
    if (sortAPIList.indexOf(config.url) > -1) {
      sharedParams = {
        ...sharedParams,
        column: 'sort',
        order: 'asc',
      }
    }

    // 这里顺序一定要在column: 'createTime'设置之后
    if (homeSortAPIList.indexOf(config.url) > -1) {
      sharedParams = {
        ...sharedParams,
        column: 'homeSort',
        order: 'asc',
      }
    }
    // indexOf()方法返回在数组中可以找到一个给定元素的第一个索引，如果不存在，则返回-1。

    if (analyticsTrackAPIList.indexOf(config.url) > -1) {
      sharedParams = {
        ...sharedParams,
        channel,
        clientOsString: device.os,
      }
    }

    //在URL部分定义全局筛选条件
    config.params = {
      ...sharedParams,
      ...config.params,
    }

    if (config.method == 'post' && Object.prototype.toString.call(config.data) != '[object FormData]') {
      config.data = {
        ...sharedParams,
        ...config.data,
      }
    }

    //拼接GET参数
    const url = config.url
    if (config.method.toUpperCase() === 'GET') {
      const parameters = config.data

      if (parameters && parameters.constructor === Object && Object.keys(parameters).length > 0) {
        var getParameters = ''
        var isFristElement = true

        for (const key in parameters) {
          if (isFristElement) {
            isFristElement = false
            getParameters += key + '=' + parameters[key]
          } else {
            getParameters += '&' + key + '=' + parameters[key]
          }
        }
        config.url = config.url + '?' + getParameters
      }
    }

    const signParameters = {
      ...config.params,
      ...config.data,
    }

    //去掉 Url 里的时间戳 与后端算法保存一致
    delete signParameters._t

    let sign = signMd5Utils.getSign(url, signParameters)

    // console.log('\n\n request token:' + JSON.stringify(token) + '\n\n');
    let tenantid = Vue.ls.get(TENANT_ID)
    if (!tenantid) tenantid = '0'
    let signHeader = {
      'X-Sign': sign,
      'X-TIMESTAMP': timestamp,
      'X-Access-Token': token,
      'tenant-id': tenantid,
    }
    config.headers = signHeader

    config.url = encodeURI(config.url)

    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use((response) => {
  return response.data
}, err)

const installer = {
  vm: {},
  install(Vue, router = {}) {
    Vue.use(VueAxios, router, service)
  },
}
/**
 * Blob解析
 * @param data
 */
function blobToJson(data) {
  let fileReader = new FileReader()
  let token = Vue.ls.get(ACCESS_TOKEN)
  fileReader.onload = function () {
    try {
      let jsonData = JSON.parse(this.result) // 说明是普通对象数据，后台转换失败
      console.log('jsonData', jsonData)
      if (jsonData.status === 500) {
        console.log('token----------》', token)
        if (token && jsonData.message.includes('Token失效')) {
          Modal.error({
            title: '登录已过期',
            content: '很抱歉，登录已过期，请重新登录',
            okText: '重新登录',
            mask: false,
            onOk: () => {
              store.dispatch('user/Logout').then(() => {
                Vue.ls.remove(ACCESS_TOKEN)
                window.location.reload()
              })
            },
          })
        }
      }
    } catch (err) {
      // 解析成对象失败，说明是正常的文件流
      console.log('blob解析fileReader返回err', err)
    }
  }
  fileReader.readAsText(data)
}

export { installer as VueAxios, service as axios }
